package com.project.slsx.activity;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.project.slsx.Constant.Constans;
import com.project.slsx.R;
import com.project.slsx.adapter.NewMSAdapter;
import com.project.slsx.bean.NewShangMengBean;
import com.project.slsx.utils.ParamsUtils;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 新商盟
 */
public class NewShangMengActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = NewShangMengActivity.class.getSimpleName();
    private int type = 0;
    private boolean sort = false;
    private NewMSAdapter adapter;
    private RecyclerView rv;

    private ArrayList<NewShangMengBean.ResultBean> resultBeans = new ArrayList<>();
    private WebView mWebView;

    @Override
    public int getLayoutId() {
        return R.layout.activity_new_shang_meng;
    }

    @Override
    public void initView() {
        TextView title = findViewById(R.id.tv_title);
        title.setText("新商盟");
        findViewById(R.id.rl_back).setOnClickListener(v -> finish());
        mWebView = findViewById(R.id.webview);
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(false); // 缩放至屏幕的大小
        webSettings.setDomStorageEnabled(true);

        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        mWebView.getSettings().setLoadWithOverviewMode(true);
        //缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件

        //其他细节操作
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式


        TextView tvName = findViewById(R.id.tv_new_name);
        TextView tvSail = findViewById(R.id.tv_new_sail);
        TextView tvTotal = findViewById(R.id.tv_new_total);
        tvName.setOnClickListener(this);
        tvSail.setOnClickListener(this);
        tvTotal.setOnClickListener(this);

        rv = findViewById(R.id.recyclerview_new_mengshang);
        rv.setLayoutManager(new LinearLayoutManager(this));
        adapter = new NewMSAdapter(R.layout.layout_item_new_mengshang);
        rv.setAdapter(adapter);

    }

    @Override
    public void initData() {
        getGoodList();

        //新商盟 h5
        mWebView.loadUrl(Constans.NSM);
        mWebView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });

        mWebView.setOnKeyListener((v, keyCode, event) -> {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                //按返回键操作并且能回退网页
                if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
                    //后退
                    mWebView.goBack();
                    return true;
                }
            }
            return false;
        });
    }

    private void getGoodList() {
        HttpParams xinshangmengParams = ParamsUtils.getXinshangmengParams();
        xinshangmengParams.put("type", type);
        xinshangmengParams.put("sort", sort ? 0 : 1);
        OkGo.<String>post(Constans.BASEURL).tag("xinshangmeng").params(xinshangmengParams).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                Log.i(TAG, "onSuccess: ");
                NewShangMengBean newShangMengBean = JSONObject.parseObject(response.body(), NewShangMengBean.class);
                if (newShangMengBean.getErrno() == Constans.SUCCESS) {
                    List<NewShangMengBean.ResultBean> result = newShangMengBean.getResult();
                    //对结果排序
                    if (result != null && result.size() > 0) {
                        adapter.setNewData(result);
                    } else {
                        showToast(mContext, "无数据");
                    }

//                    sortResult(result);
                } else {
                    showToast(mContext, newShangMengBean.getErrmsg());

                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                Log.i(TAG, "onError: ");
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }
        });
    }

    @Override
    protected void onDestroy() {
        if (mWebView != null) {
            mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            mWebView.clearHistory();
            ((ViewGroup) mWebView.getParent()).removeView(mWebView);
            mWebView.destroy();
            mWebView = null;
        }
        super.onDestroy();
    }

    /**
     * 拍讯
     *
     * @param result
     */
    private void sortResult(List<NewShangMengBean.ResultBean> result) {
        Collections.sort(result, new Comparator<NewShangMengBean.ResultBean>() {
            @Override
            public int compare(NewShangMengBean.ResultBean o1, NewShangMengBean.ResultBean o2) {
                int sail1 = Integer.valueOf(o1.getSailed());
                int sail2 = Integer.valueOf(o2.getSailed());
                if (sail1 < sail2) {
                    return 1;
                } else {
                    return -1;
                }

            }
        });

        int size = result.size();
        for (int i = 0; i < size; i++) {
            Log.i(TAG, "sortResult:  " + result.get(i).getSailed());
        }

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.tv_new_name:
                type = 0;
                sort = !sort;
                getGoodList();
                break;

            case R.id.tv_new_sail:
                type = 1;
                sort = !sort;
                getGoodList();
                break;

            case R.id.tv_new_total:
                type = 2;
                sort = !sort;
                getGoodList();
                break;
        }
    }
}
